<template>
    <div id="learn-model">
        <el-dialog
            title="正在学习..."
            v-model="modelDialog" 
            draggable 
            :close-on-click-modal="false" 
            :fullscreen="true"
            :before-close="handleClose"
            :destroy-on-close="true"
        >
            <span v-if="isPageVisible">
                <template v-if="fileType === 'docx'">
                    <vue-office-docx
                        :src="fileSrc"
                        class="file-s"
                        @rendered="renderedHandler"
                        @error="errorHandler"
                    />
                </template>
                <template v-if="fileType === 'xlsx'">
                    <vue-office-excel
                        :src="fileSrc"
                        class="file-s"
                        @rendered="renderedHandler"
                        @error="errorHandler"
                    />
                </template>
                <template v-if="fileType === 'pdf'">
                    <object :data="fileSrc" type="application/pdf" class="file-s" @load="pdfLoaded" @error="pdfFailed">
                        <embed :src="fileSrc" type="application/pdf" />
                    </object>
                </template>
                <template v-if="fileType === 'mp4'">
                    <div class="video-s">
                        <video ref="videoRef" class="video-con" controls autoplay preload="auto" @play="onVideoPlay" @pause="onVideoPause" @ended="onVideoEnded">
                            <source :src="fileSrc" type="video/mp4">
                        </video>
                    </div>
                </template>
            </span>
            <span v-else>
                <h3>您已离开学习，请点击右下角继续学习按钮...</h3>
            </span>
            
            <template #footer>
                <el-button v-if="!isPageVisible" @click="continueHandel">继续学习</el-button>
                <el-button @click="cancelUseClick" type="warning">退出学习</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRef , toRefs , toRaw , onMounted , nextTick, watch } from 'vue';
import { ElButton, ElDialog, ElMessage } from 'element-plus';
import { EduStudyOLAdd } from '/@/api/centerControl/sms';
import { getUserInfo } from '/@/api/user';
// docx
import VueOfficeDocx from '@vue-office/docx'; //引入VueOfficeDocx组件
import '@vue-office/docx/lib/index.css'; //引入相关样式

// excel
import VueOfficeExcel from '@vue-office/excel'; //引入VueOfficeExcel组件
import '@vue-office/excel/lib/index.css'; //引入相关样式

export default defineComponent( {
    name: 'learn-model',
    components: { VueOfficeDocx , VueOfficeExcel },
    props: {
        modelDialog:{
            type: Boolean,
            default: false,
        },
        learnInfo: {
            type: String,
            default: '',
        }
    },
    setup(props,ctx){
        let apiUrl = import.meta.env.VITE_API_URL + '/';
        const fileSrc = ref();
        const fileType = ref();
        const intervalId: any = ref(null);
        let userInfo:any = '';
        const isPageVisible = ref(true);
        const videoRef: any = ref(null);
        let timeArr: any = [];

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        }

        /*** PDF渲染成功 */
        const pdfLoaded = () => {
            console.log('渲染成功')
            creatLearnFun();
        }

        /*** PDF渲染失败 */
        const pdfFailed = () => {
            ElMessage({
                type: 'error',
                message: '文件渲染失败，请联系管理员',
                duration: 1500,
                onClose: () => {
                    clearTimeFun();
                },
            });
        }

        /*** 清除定时器 */
        const clearTimeFun = () => {
            if(timeArr.length !== 0){
                timeArr.map((i: any) => {
                    clearInterval(i);
                    i = null;
                });
            }
        }

        /*** 视频自动暂停函数 */
        const pauseFun = async() => {
            if(videoRef.value && fileType.value === 'mp4') videoRef.value.pause(); // 视频自动暂停 
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = async() => {
            await pauseFun();
            console.log(intervalId.value,'intervalId0')
            setTimeout(() => {
                fileSrc.value = '';
                fileType.value = '';
                clearTimeFun();
                ctx.emit('cancelModelClick');
            },0);
        }

        /*** 挂机检测 */
        const handleVisibilityChange = () => {
            if (document.visibilityState === 'hidden') {
                if(videoRef.value && fileType.value === 'mp4') videoRef.value.pause(); // 视频自动暂停 
                isPageVisible.value = false;
                clearTimeFun();
            }
        };

        /*** 继续学习 */
        const continueHandel = () => {
            if(videoRef.value && fileType.value === 'mp4') videoRef.value.play(); // 视频自动播放
            isPageVisible.value = true;
            creatLearnFun();
        }

        /*** 监听modelDialog的变化 */
        watch(() => props.modelDialog,(newVal) => {
            if(newVal){
                document.addEventListener('visibilitychange', handleVisibilityChange);
                isPageVisible.value = true;
                getData();
                let ipConfig = apiUrl + JSON.parse(JSON.parse(props.learnInfo).learnRecord).filePath + '/' + JSON.parse(JSON.parse(props.learnInfo).learnRecord).fileObjectName;
                console.log(ipConfig,'ipConfig')
                fileSrc.value = ipConfig;
                fileType.value = JSON.parse(JSON.parse(props.learnInfo).learnRecord).fileSuffix;
            }
        })

        onMounted(() => {
            nextTick(() => {});
        })

        /*** getData 获取数据 */
        const getData = async() => {
            let res: any = await getUserInfo();
            if(res.success) userInfo = res.data;
        }

        /*** creatLearnFun 创建学习函数 */
        const creatLearnFun = () => {
            creatLearnFunImpl();
            intervalId.value = setInterval(() => {
                creatLearnFunImpl();
            },2000);
            timeArr.push(intervalId.value);
        }
        const creatLearnFunImpl = async() => {
            let param: any = {};
            param.l_TrainingPlanId = JSON.parse(props.learnInfo).l_TrainingPlanId;
            param.l_SysUserId = userInfo.id;
            param.n_AddCumulativeMin = Number(1);
            let res: any = await EduStudyOLAdd(param);
            // console.log(res,'res')
            if(res.success) return;
        }

        /*** renderedHandler docx作为参数通过父组件传参 */
        const renderedHandler = () => {
            creatLearnFun();
        }

        /*** errorHandler 渲染失败 */
        const errorHandler = () => {
            ElMessage({
                type: 'error',
                message: '文件渲染失败，请联系管理员',
                duration: 1500,
                onClose: () => {
                    clearTimeFun();
                },
            });
        }

        /*** onVideoPlay 视频已开始播放 */
        const onVideoPlay = () => {
            creatLearnFun();
        }

        /*** onVideoPause 视频暂停 */
        const onVideoPause = () => {
            clearTimeFun();
        }

        /*** onVideoEnded 视频结束 */
        const onVideoEnded = () => {
            clearTimeFun();
        }

        /*** modelDialog 响应弹窗的关闭  */
        const modelDialog = computed(() => {
            return props.modelDialog
        })

        return {
            handleClose,
            cancelUseClick,
            modelDialog,
            renderedHandler,
            errorHandler,
            fileSrc,
            fileType,
            onVideoPlay,
            onVideoPause,
            onVideoEnded,
            isPageVisible,
            continueHandel,
            videoRef,
            pdfFailed,
            pdfLoaded,
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-dialog__body){
    height: calc(100vh - 110px);
    max-height: none!important;
    overflow-y: hidden;
}
.file-s{
    // padding: 20px 0;
    height: calc(100vh - 120px);
    overflow-y: auto;
    width: 100%;
    background-color: rgba(255,255,255,0);
}
.video-s{
    height: 100%;
    .video-con{
        background: rgba(229, 232, 243, 0.2);
        width: 100%;
        height: 100%;
    }
}
</style>